import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../store'
import Test from '../views/test/test.vue'
import Login from '../views/login.vue'
import Index from '../views/index.vue'
import Home from '../views/home/home.vue'
import User from '../views/user/list.vue'
import GoodsList from '../views/goods/list.vue'
import GoodsAuditList from '../views/goods/audit-list.vue'
import GoodsAudit from '../views/goods/audit.vue'
import NewsList from '../views/news/list.vue'
import NewAuditList from '../views/news/audit-list.vue'

export const dynamicRouter: Array<RouteRecordRaw> = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      icon: 'Platform'
    }
  },
  {
    path: '/user',
    name: 'User',
    component: User,
    meta: {
      title: '用户管理',
      icon: 'User'
    },
  },
  {
    path: '/goods',
    name: 'Goods',
    meta: {
      title: '商品管理',
      icon: 'ShoppingBag'
    },
    children: [
      {
        path: '/goods/list',
        name: 'GoodsList',
        component: GoodsList,
        meta: {
          title: '商品列表'
        },
      },
      {
        path: '/goods/audit-list',
        name: 'GoodsAuditList',
        component: GoodsAuditList,
        meta: {
          title: '商品待审核列表'
        }
      },
      {
        path: '/audit',
        name: 'GoodsAudit',
        component: GoodsAudit,
        meta: {
          title: '商品审核',
          hide: true
        }
      },
    ]
  },
  {
    path: '/news',
    name: 'News',
    meta: {
      title: '动态管理',
      icon: 'Notebook'
    },
    children: [
      {
        path: '/news/list',
        name: 'News',
        meta: {
          title: '动态列表'
        },
        component: NewsList,
      },
      {
        path: '/news/audit-list',
        name: 'NewsAuditList',
        meta: {
          title: '动态审核列表'
        },
        component: NewAuditList,
      }
    ]
  },
  {
    path: '/category',
    name: ' Category',
    meta: {
      title: '分类管理',
      icon: 'icon-menu'
    },
    component: () => import('@/views/category/list.vue'),
  },
  {
    path: '/banner',
    name: ' Banner',
    meta: {
      title: '轮播图管理',
      icon: 'Picture'
    },
    component: () => import('@/views/banner/list.vue'),
  }
]

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Index',
    component: Index,
    redirect: '/home',
    children: dynamicRouter
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/test',
    name: 'Test',
    component: Test
  }
]

// console.log(process.env)

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from) => {
  const token = useUserStore().user.token
  if (to.name !== 'Login' && !token) {
    return { name: 'Login' }
  }
  return
})

export default router
